<?php
declare(strict_types=1);

// 导航高亮显示
function nav_active(string $nav, string $class = ' class="active"'): string
{
    return ($nav == get_controller()) ? $class : '';
}

// form-select生成
function form_select(string $name, $options, $selected = '', string $attr = ''): string
{
    if (!is_array($options)) {
        $options = str_to_array($options);
    }
    if (!empty($attr)) {
        $attr = ' ' . clear_html($attr);
    }
    $selected = is_array($selected) ? $selected : explode(',', strval($selected));
    $select = '<select name="' . $name . '"' . $attr . '>' . "\n";
    foreach ($options as $k => $v) {
        $select .= "\t<option value=\"{$k}\"" . (in_array($k, $selected) ? ' selected="selected"' : '') . ">{$v}</option>\n";
    }
    return $select . "</select>\n";
}

// form-radio生成
function form_radio(string $name, $options, $selected = '', string $attr = '', bool $is_label = false): string
{
    if (!is_array($options)) {
        $options = str_to_array($options);
    }
    if (!empty($attr)) {
        $attr = ' ' . clear_html($attr);
    }
    $radio = '';
    foreach ($options as $k => $v) {
        if ($is_label) {
            $radio .= '<label' . $attr . '><input type="radio" name="' . $name . '" value="' . $k . '"' . ($k == $selected ? ' checked="checked"' : '') . ' />' . $v . '</label>' . "\n";
        } else {
            $radio .= '<input type="radio" name="' . $name . '" value="' . $k . '" title="' . $v . '"' . ($k == $selected ? ' checked="checked"' : '') . ' />';
        }
    }
    return $radio;
}

// 格式化输出IP
function ip_format(int $ip): string
{
    return preg_replace('/(\d+)\.(\d+)\.(\d+)\.(\d+)/i',"$1.$2.*.$4", long2ip($ip));
}


// 获取用户昵称
function get_nickname(int $id): string
{
    $user = db('user')->where('status=1')->cache()->column('nickname', 'id');
    return $user[$id] ?? '无名';
}